# -*- coding: utf-8 -*-
"""
@File    : xizang_rikazeshi_policy
@Author  : caojy
@Time    : 24/12/03 10:27
"""
import datetime
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XizangRikazeshiPolicy(BaseTaxPolicySpider):
    name = 'xizang_rikazeshi_policy'

    province = '西藏自治区'
    city = '日喀则市'
    county = ''
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['日喀则市人民政府', '', 'http://www.rikaze.gov.cn/info-public-xzgfxwjk-list-single.thtml?id=15559'],
            ['日喀则市教育局', '', 'http://jyj.rikaze.gov.cn/info-public-item-list-single.thtml?id=14787'],
            ['日喀则市民政局', '', 'http://mzj.rikaze.gov.cn/public-policy.thtml?id=14645'],
            ['日喀则市财政局', '', 'http://czj.rikaze.gov.cn/public-policy.thtml?id=14411'],
            ['日喀则市人力资源和社会保障局', '', 'http://rsj.rikaze.gov.cn/public-policy.thtml?id=13731'],
            ['日喀则市自然资源局', '', 'http://zrzyj.rikaze.gov.cn/public-policy.thtml?id=14559'],
            ['日喀则市旅游发展局', '', 'http://lfj.rikaze.gov.cn/public-policy.thtml?id=13045'],
            ['日喀则市退役军人事务局', '', 'http://tyjrswj.rikaze.gov.cn/public-policy.thtml?id=13303'],
            ['日喀则市市场监督管理局', '', 'http://sjj.rikaze.gov.cn/public-policy.thtml?id=13002'],
            ['日喀则市桑珠孜区人民政府', '桑珠孜区', 'http://www.sangzhuzi.gov.cn/public-policy.thtml?id=14962'],
            ['日喀则市桑珠孜区人民政府', '桑珠孜区', 'http://www.sangzhuzi.gov.cn/public-policy.thtml?id=14963'],
            ['日喀则市江孜县人民政府', '江孜县', 'http://www.jiangzi.gov.cn/public-policy.thtml?id=15085'],
            ['日喀则市江孜县人民政府', '江孜县', 'http://www.jiangzi.gov.cn/public-policy.thtml?id=15086'],
            ['日喀则市白朗县人民政府', '白朗县', 'http://www.blx.gov.cn/public-policy.thtml?id=11579'],
            ['日喀则市白朗县人民政府', '白朗县', 'http://www.blx.gov.cn/public-policy.thtml?id=11580'],
            ['日喀则市亚东县人民政府', '亚东县', 'http://www.ydx.gov.cn/public-policy.thtml?id=11466'],
            ['日喀则市亚东县人民政府', '亚东县', 'http://www.ydx.gov.cn/public-policy.thtml?id=11467'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='tab-item show' or @class='new-lists' or @class='list-item']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=2] |"
                "//ul[@class='zfxxgk-nr-cnet']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=2]"
        ):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.thtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            # pages = response.xpath("//script").re_first(r"""createPageHTML\('page_?-?div',(\d+),""") or response.xpath("//script").re_first(r"""createPageHTML\('paging',(\d+),""") or 0
            count = response.xpath(".").re_first(r"count[:：]?\s*(\d+)")
            if count:
                pages = math.ceil(int(count)/10)
                print(response.url, f"page: {pages}")
                for page_num in range(2, int(pages) + 1):
                    url = response.url + f"&pn={page_num}"
                    yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
            else:
                next_url = response.xpath("//a[text()='下一页' or text()='下页']/@href").get()
                print("next_url", next_url)
                if next_url != response.url:
                    yield response.follow(next_url, callback=self.parse_list, meta={'item': prev_item})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xizang_rikazeshi_policy".split())
